#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <poll.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/time.h>
#include <signal.h>
#include <sys/wait.h>


void *client_thread(void *arg)
{
	int client;
	int restul;
	char buffer[100];
	
	client = (int)((long)arg);
	while(1)
	{
		//读取客户端数据
		memset(buffer, 0, sizeof(buffer));
		restul = read(client, buffer, sizeof(buffer)-1);
		//读取出错
		if(restul == -1)
		{
			close(client);
			perror("read");
			pthread_exit("failed");
		}
		//对方关闭连接
		if(restul == 0)
		{
			close(client);
			pthread_exit("succeed");
		}
		//读取成功
		if(restul > 0)
		{
			//把数据写回客户端
			restul = write(client, buffer, restul);
			if(restul == -1)
			{
				close(client);
				perror("write");
				pthread_exit("failed");
			}
		}
	}
	pthread_exit("succeed");
}

int main(int argv, char *argc[])
{
	int i;
	int sock;
	int client;
	int restul;
	int max_fd;
	pthread_t tid;
	socklen_t addr_lenght;
	struct sockaddr_in client_addr;
	struct sockaddr_in server_addr;
	char *ip = "0.0.0.0";
	char *port = "5007";
	int optval = 1;
	
	if(argv > 1)
		ip = argc[1];
	if(argv > 2)
		port = argc[2];
	
	//创建套接字
	sock = socket(AF_INET, SOCK_STREAM, 0);
	if(sock == -1)
	{
		perror("socket");
		return -1;
	}
	
	//允许端口重用
	if(setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&optval, sizeof(int)) == -1)
	{
		close(sock);
		perror("setsockopt");
		return -1;
	}
	
	//绑IP和端口
	memset(&server_addr, 0, sizeof(server_addr));
	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(atoi(port));
	server_addr.sin_addr.s_addr = inet_addr(ip);
	if(bind(sock, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1)
	{
		close(sock);
		perror("bind");
		return -1;
	}
	printf("IP %s; port %d\n", inet_ntoa(server_addr.sin_addr), ntohs(server_addr.sin_port));
	
	//监听套接字
	if(listen(sock, 100) == -1)
	{
		close(sock);
		perror("listen");
		return -1;
	}
	
	while(1)
	{
		//获取监听到的客户端描述符
		addr_lenght = sizeof(client_addr);
		client = accept(sock, (struct sockaddr *)&client_addr, &addr_lenght);
		if(client == -1)
		{
			perror("accept");
			//关闭所有描述符	
			max_fd=getdtablesize();
			for(i=0; i<=max_fd; i++)
			{
				close(i);
			}
			return -1;
		}
		
		//创建子线程
		restul = pthread_create(&tid, NULL, client_thread, (void*)((long)client));
		if(restul != 0)
		{
			close(client);
			printf("pthread_create failed;error code %d\n", restul);
			continue;
		}
		//脱离子线程
		restul = pthread_detach(tid);
		if(restul != 0)
		{
			close(client);
			printf("pthread_detach failed;error code %d\n", restul);
			continue;
		}
	}
}
